package com.lwz.msm.controller;

import com.lwz.msm.service.MsmService;
import com.lwz.msm.util.RandomUtil;
import com.lwz.util.R;
import com.mysql.cj.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Lw中
 * @date 2020/11/18 11:22
 */

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * LWZ TODO : 2020/11/18 信息发送接口
     */

    /**
     * 发送短信方法
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public R senMsm(@PathVariable String phone) {
        // 先从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        // 生成随机值传递给阿里云使用
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        System.out.println(code);
        Boolean isSend = msmService.send(map, phone);
        if (isSend) {
            //如果发送成功，将验证码以key\value形式存储在redis中并设置5分钟有效时间
            redisTemplate.opsForValue().set("phone", code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }

}
